package net.bithappens.hnqe.impl.rest.provider;

import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;

import net.bithappens.hnqe.IllegalParamException;
import net.bithappens.hnqe.graph.EntryValue;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class CalendarJsonAddapter implements JsonSerializer<Object>, JsonDeserializer<Object> {

	
	@Override
	public JsonElement serialize(Object object, Type type, JsonSerializationContext jsonSerializationContext) {
		
		JsonObject jsonCalValue = new JsonObject();
			
		jsonCalValue.addProperty("milliseconds", ((Calendar)object).getTime().getTime());
		
		return jsonCalValue;
		
	}
	
	
	@Override
	public Object deserialize(JsonElement jsonElement, Type type, 
		JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
	
		JsonObject jsonObj = jsonElement.getAsJsonObject();

		if(jsonObj.get("milliseconds") != null){
			long time = jsonObj.get("milliseconds").getAsLong();
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(time);
			return cal;
		}
		
		return jsonDeserializationContext.deserialize(jsonElement, type);
	}	
}
